<?php
include '../includes/cPage.php';
include '../includes/cDatabase.php';
include '../includes/variables.php';
include '../includes/cPlayer.php';
include '../includes/cMember.php';
include '../includes/cGame.php';
include '../includes/cTransfer.php';
include '../includes/cDates.php';

$cPage = new page("User Login");
echo $cPage->getTitle();
echo $cPage->pageStringStart();
echo $cPage->contentStringStart();

// Test variables to hack into the user login if required.
$user = "test";
$password = "test";

$cDatabase = new database();

$connect = $cDatabase->connectToDatabase();
$activeDatabase = $cDatabase->getActiveDatabase($connect);
$db = $cDatabase->selectDatabase($connect, $activeDatabase);

$cGame = new game();

$userLoginEnabled = $cDatabase->GetUserLoginEnabled($connect);
$captainsEnabled = $cDatabase->GetCaptainsEnabled($connect);
$maxWeeks = $cDatabase->GetMaxWeeks($connect);
			
if (@$_GET['form'] == "login")
{
	// FORM = select
	// Select team page - directly after the user has logged in
	$MemberIndex = array();
	$teamNumber = 0;	// The number of teams owned by a single person
	
	// Check user and password 
	for ($memberNumber = 0; $memberNumber < $cGame->numberOfMembers; $memberNumber++)
	{
		if ($cGame->getMemberFromUsername($memberNumber, $_POST['loginName'], $_POST['password']) == 1)
		{
			$MemberIndex[$teamNumber] = $memberNumber;
			$teamNumber++;
		}
	}
	//if ($_POST['loginName'] == $user && $_POST['password'] == $password) - // test case
	if ($teamNumber > 0)
	{
		echo "<FORM ACTION='$PHP_SELF?form=select' METHOD='POST'>";
		echo "<table>";
		echo "<select name=\"selectTeam\">";
		for ($i = 0; $i < $teamNumber; $i++)
		{
			$teamName = $cGame->cMember[$MemberIndex[$i]]->getTeamName();
			echo "<option value = '".$teamName;
			echo "'>" .$teamName. "</option>";
		}
		echo "</select>";
		echo "<input name=\"selectTeamButton\" type=\"submit\" id=\"selectTeam\" value=\"Select Team\">";
		echo "</table>";
		echo "</form>";
	}
	else
	{
		echo "ERROR: Login is incorrect.";
	}
}
else if (@$_GET['form'] == "select")
{
	// FORM = action
	// The user has now logged in
	$teamName = $_POST['selectTeam'];
	$selectArray[0] = '*';
	$result = $cDatabase->selectFromDatabase($connect, 'memberlist', $selectArray, "teamName", $teamName, NULL, NULL);
	$row = mysqli_fetch_array($result, MYSQLI_ASSOC);
			
	echo "<BR>Member Name: ".$row['memberName'];
	echo "<BR>Team Name: ".$teamName;
	//echo "<BR>IP: ".@$REMOTE_ADDR; 

	?>
	<div align="center">
	  	<table border='0'>
			<tr><td>
				<form action="<?php echo $_SERVER['PHP_SELF'] ?>?form=captain&teamName=<?php echo $teamName ?>" method="POST">
					<input id="fflbutton" name="changeCaptainButton" type="submit" id="changeCaptain" value="Change Captain">
				</form>
			</td></tr>
			<tr><td>
				<form action="<?php echo $_SERVER['PHP_SELF'] ?>?form=transfer&teamName=<?php echo $teamName ?>" method="POST">
					<input id="fflbutton" name="transferPlayerButton" type="submit" id="transferPlayer" value="Transfer Player">
				</form>
			</td></tr>
	  	</table>
	</div>
	<?php
}
else if (@$_GET['form'] == "changeCaptain")
{
	// This is the section where we change the member's captain
	echo "<BR>Change captain ".$teamName." for week ".$week." onwards";
	$captain = $_POST['selectCaptain'];
	echo "<BR>Captain in ".$captain;
	
	for ($i = $week; $i <=$maxWeeks ; $i++)
	{
		$query = "UPDATE memberlist SET ".getCaptainVariable($i)." = '".$captain."' WHERE teamName='".$teamName."'";
		//echo "<BR>".$query;
		
		$result |= mysqli_query($connect, $query);
	}
	
	if ($result == 1)
	{
		echo "<BR>Captain changed at ";
		// Write to captain's log
		$today = getdate();
		echo date('l jS \of F Y h:i:s A')."<BR>";
		
		$selectArray[0] = '*';
		$result = $cDatabase->selectFromDatabase($connect, 'captainLog', $selectArray, NULL, NULL, NULL, NULL);

		$index = mysqli_num_rows($result) + 1;
		
		$cDatabase->insertCaptainLog($connect, $today['year'], $today['mon'], $today['mday'], date('h'), date('i'), 
			date('s'), $week, $teamName, $captainOut, $captain, $index);
	}
	else
	{
		echo "<BR>ERROR";
	}
}
else if (@$_GET['form'] == "captain")
{
	// This is the section where we select the member's new captain
	$cTransfer = new transfer();
	
	// Get week and day. We can only change the captain on a Monday or Tuesday
	$cDates = new dates;
	$currentWeek = $cDates->getCurrentWeek();
	//$currentWeek = 1;	// test code
	$day = $cDates->getToday();
	
	echo "<BR>Today is ".$day;
	echo "<BR>Current week :".$currentWeek;
	if ($currentWeek < 1)
	{
		// The season hasn't started yet
		$startDay = date("D",$cDates->getStartDateFromWeek($currentWeek+1)); 
		echo "<BR>Pre season to ".$startDay." ".date("d-m-Y",$cDates->getStartDateFromWeek($currentWeek+1));
	}
	else
	{
		echo "<BR>".date("d-m-Y",$cDates->getStartDateFromWeek($currentWeek));
		echo " to ".date("d-m-Y",$cDates->getEndDateFromWeek($currentWeek));
	}
		//$day = 'Tuesday';	// LUSH test
	if ($currentWeek > $cDates->maxWeeks)
	{
		// This is post season - no need to allow captain transfers now
		echo "<BR><BR>Post season - captains cannot be transferred at this point";
	}
	else if ( (($cTransfer->checkCaptainTransferOK($day, $currentWeek) == 0) && ($currentWeek > 1)) || 
		(($currentWeek == 1) && (($day == 'Saturday') || ($day == 'Sunday'))) )
	{
		// We cannot change the captain on this day
		echo "<BR><BR>Captains can only be changed before the start of the week i.e. on Monday or Tuesday";
		echo "<BR>Weeks run from Tuesday until Monday the following week.";
	}
	else
	{
		// We can transfer captains up until Saturday on the first week anytime and on Mondays and Tuesday thereafer
		if ($currentWeek < 1)
			$thisWeek = 1;
		else
			$thisWeek = $currentWeek;
		
		// Get current players in team and our current captain
		$playerTeamCode = $cTransfer->getTeamPlayerCodes($teamName);
		$currentCaptainCode = $cTransfer->getCaptainCodeForWeek($teamName, $thisWeek);
		$currentCaptainName = $cTransfer->getPlayerName($currentCaptainCode);
			
		if ($day == 'Monday')
		{
			// it's the week before - so we want to change the captain for the next week
			$captainChangeWeek = $currentWeek + 1;
		}
		else if (($day = 'Tuesday') || ($day = 'Wednesday') || ($day = 'Thursday') || ($day = 'Friday'))
		{
			// it's the first day of a new week
			$captainChangeWeek = $currentWeek;
		}
		$startDate = date("d-m-Y",$cDates->getStartDateFromWeek($captainChangeWeek));
		$startDay = date("D",$cDates->getStartDateFromWeek($captainChangeWeek)); 
		
		echo "<BR><BR>Current captain ".$currentCaptainCode." - ".$currentCaptainName;
		echo "<BR><BR>";
		if ($currentWeek > 0)
		{
			echo "You will be changing your captain from week ".$captainChangeWeek." (".$startDay." ".$startDate.") onwards<BR>";
		}
		else
		{
			echo "You will be changing your captain from week 0 onwards<BR>";
		}
		?>
			<form action="<?php echo $_SERVER['PHP_SELF'] ?>?form=changeCaptain&teamName=<?php echo $teamName ?>&week=<?php echo $captainChangeWeek ?>&captainOut=<?php echo $currentCaptainCode ?>" method="POST">
		  		<table border='0'>
					<tr>
					<td>
		    			<select name="selectCaptain">
						<?php
						for ($i = 1; $i <= sizeof($playerTeamCode); $i++)
						{
							if ($playerTeamCode[$i] != NULL)
		    		  			echo"<option value = '" .$playerTeamCode[$i]. "'>" .$playerTeamCode[$i]." - ".$cTransfer->getPlayerName($playerTeamCode[$i])."</option>";
						}
						?>
				        </select>
			    		New Captain
					</td>
					<td><input name="changeCaptainButton" type="submit" id="changeCaptain" value="Change Captain"></td>
					</tr>
				</table>
			</form>
		<?php
	}
}
else if (@$_GET['form'] == "transfer")
{
	// This is the section where we do a member transfer
	$cTransfer = new transfer();
	
	//$cTransfer->selectTransfer($teamName, $transfersRemaining);
	echo "<BR>Please submit transfers to Tim Lush via email.";
}
else if ($userLoginEnabled == 1)
{
	// FORM = login
	// This is the login menu - the first point of call for this page
	?>
	<div align="center">
	<form action="<?php echo $_SERVER['PHP_SELF'] ?>?form=login" method="POST">
	  <table width='400' border='0'>
	    <tr>
	      <td><div align="center">Login Name</div></td>
	      <td><div align="center">Password</div></td>
	    </tr>
	    <tr>
	      <td><div align="center">
	        <input type='text' name='loginName' size='20' maxlength='30' value=<?php echo @$_POST['loginName'] ?>>
	      </div></td>
	      <td><div align="center">
	        <input type='password' name='password' size='20' maxlength='30' value=<?php echo @$_POST['password'] ?>>
	      </div></td>
	    </tr>
		<tr>
		  <td colspan="2" align="center">
		    <p>&nbsp;</p>
		    <p><input name="loginButton" type="submit" id="login" value="LOGIN">
	        </p></td>
	 	</tr>
	  </table>
	</form>
	</div>
	<?php
}
else if ($userLoginEnabled == 0)
{
	// The default case for seasons where logins are not enabled
	echo "Login screen not active for this season.";
}

echo $cPage->getContentStringEnd();
echo $cPage->getMenu();
echo $cPage->getClear();
echo $cPage->pageStringEnd();
echo $cPage->getFooter();
?>